package com.ddh.codeduck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeduck.pojo.entity.CodeDuckQuestionTag;
import com.codeduck.pojo.entity.CodeDuckTag;
import com.ddh.codeduck.mapper.CodeDuckQuestionTagMapper;
import com.ddh.codeduck.service.ICodeDuckQuestionTagService;
import com.ddh.codeduck.service.ICodeDuckTagService;
import com.ddhcodeduck.common.exception.BusinessException;
import com.ddhcodeduck.common.exception.ErrorCode;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 题目-标签多对多关联表 服务实现类
 * </p>
 *
 * @author ddh
 * @since 2025-07-10
 */
@Service
public class CodeDuckQuestionTagServiceImpl extends ServiceImpl<CodeDuckQuestionTagMapper, CodeDuckQuestionTag> implements ICodeDuckQuestionTagService {

    @Resource
    private ICodeDuckTagService codeDuckTagService;

    @Override
    public List<CodeDuckTag> listTagsByQuestionId(String questionId) {
        // 1. 查询关联的标签ID
        LambdaQueryWrapper<CodeDuckQuestionTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(questionId != null, CodeDuckQuestionTag::getQuestionId, questionId);

        List<CodeDuckQuestionTag> codeDuckQuestionTags = list(queryWrapper);
        if (CollectionUtils.isEmpty(codeDuckQuestionTags)) {
            throw new BusinessException(ErrorCode.QUESTION_NOT_TAG_ERROR);
        }
        //取出每一个标签id
        List<String> tagIdList = codeDuckQuestionTags.stream()
                .map(CodeDuckQuestionTag::getTagId)
                .collect(Collectors.toList());

        //根据标签id去查询标签信息
        return codeDuckTagService.listByIds(tagIdList);
    }
}
